package com.sunda.spmsorder.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sunda.spmscommon.ResponseResult;
import com.sunda.spmsorder.entity.OrderWorkshop;
import com.sunda.spmsorder.entity.OrderWorkshopDtl;
import com.sunda.spmsorder.entity.vo.OrderWorkshopQueryResultVo;
import com.sunda.spmsorder.entity.vo.OrderWorkshopQueryVo;
import com.sunda.spmsorder.mapper.OrderLogMapper;
import com.sunda.spmsorder.mapper.OrderWorkshopDtlMapper;
import com.sunda.spmsorder.mapper.OrderWorkshopMapper;
import com.sunda.spmsorder.service.IOrderWorkshopService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import static com.sunda.spmscommon.Constans.*;

/**
 * <p>
 * 车间请购单 服务实现类
 * </p>
 *
 * @author Wayne
 * @since 2021-02-02
 */
@Service
public class OrderWorkshopServiceImpl extends ServiceImpl<OrderWorkshopMapper, OrderWorkshop> implements IOrderWorkshopService {

    @Autowired
    OrderWorkshopMapper orderWorkshopMapper;

    @Autowired
    OrderWorkshopDtlMapper orderWorkshopDtlMapper;

    @Autowired
    OrderLogMapper orderLogMapper;

    @Override
    public Map<String, Object> getOrderWS(String userId, String orderStatus, int pageNo, int pageSize, String applicationDateStart, String applicationDateEnd, String urgencyDegree, String spmsWsId,String authorId, String userName) {
        userName = StringUtils.isEmpty(userName) ? null : userName;
        orderStatus = orderStatus.trim().length() == 0 ? null : orderStatus;
        PageHelper.startPage(pageNo, pageSize);

        List<Map<String, Object>> mapList = orderWorkshopMapper.getOrderWS(userId, orderStatus, applicationDateStart, applicationDateEnd, urgencyDegree, spmsWsId,authorId, userName);
        PageInfo<Map<String, Object>> pageData = new PageInfo<>(mapList);
        Map<String,Object> pageInfo = new HashMap<>();
        pageInfo.put("records", pageData.getList());
        pageInfo.put("total", pageData.getTotal());
        pageInfo.put("size", pageData.getSize());
        pageInfo.put("current", pageData.getPageNum());
        pageInfo.put("pages", pageData.getPages());
        return pageInfo;
    }

    @Override
    public IPage<OrderWorkshopQueryResultVo> getOrderWS1(OrderWorkshopQueryVo orderWorkshopQueryVo) {
       
        IPage<OrderWorkshopQueryResultVo> pageRes = this.baseMapper.getOrderWS1(orderWorkshopQueryVo.getPage(), orderWorkshopQueryVo);
        return pageRes;
    }

    /**
     * {
     * 	"orderWorkshop": {
     *         "userId": "20001",
     * 		"lastName": "20001",
     * 		"subject": "GF011002-20210201-车间请购单",
     * 		"projectType": "1",
     * 		"werks": "GH01",
     *         "workshopCode": "1002",
     * 		"projectStatus": "1",
     * 		"dateRequired": "2021-05-01",
     * 		"urgency": "2",
     * 		"projectCode": "",
     * 		"justification": "申请原因",
     * 		"applicationDate": "2021-02-10",
     * 		"status": "1",
     * 		"createDate": "2021-02-02",
     * 	    "purchaseLocation": "0"
     *        },
     * 	"orderWorkshopDtl": [{
     * 			"rowId": 10,
     * 			"materialNo": "130011853",
     * 			"materialZhDesc": "马克杯 端底白瓷花13 普通包装 48PCS/CTN",
     * 			"materialEnDesc": "MUG",
     * 			"requestQty": 4,
     * 			"basicUnit": "PCS",
     * 			"brand": "",
     * 			"rowStatus": "",
     * 			"rowComment": "",
     * 			"deviceId": "",
     * 			"deviceCategory": "",
     * 			"deviceType": "",
     * 			"materialCategory": "",
     * 			"longContractCode": ""
     *        }]
     * }
     * @param jsonObject
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult addOrderWorkshop(JSONObject jsonObject) {
        if(!jsonObject.containsKey("orderWorkshop") || !jsonObject.containsKey("orderWorkshopDtl")){
            return ResponseResult.error("参数错误请重试！");
        }
        /** uuid 为Java生成用于车间请购单表头和行项目关联的标记；表头车间单号由数据库按规则自动生成；行项目车间单号由行项目新建时通过uuid关联从表头获取； */
        String uuid = UUID.randomUUID().toString().replaceAll("-","").toLowerCase();
        String userId = jsonObject.getJSONObject("orderWorkshop").getString("userId");
        try {
            JSONObject obj = jsonObject.getJSONObject("orderWorkshop");
            int resp = createOrderWs(obj, uuid);

            addOrderLog(userId,  CREATE_ORDER_WORKSHOP, uuid);

            JSONArray array = jsonObject.getJSONArray("orderWorkshopDtl");
            int result = createOrderWsDtl(array, uuid);

            return ResponseResult.success().add("新增 orderWorkshop：", resp).add("新增 orderWorkshopDtl：", result);

        }catch (Exception e){
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResponseResult.error("请求异常请重试:" + e);
        }
    }

    public int createOrderWs(JSONObject obj, String uuid){
        OrderWorkshop ows = new OrderWorkshop();
        ows.setUuid(uuid);
        ows.setUrgency(obj.getString("urgency"));
        ows.setSubject(obj.getString("subject"));
        ows.setUserId(obj.getString("userId"));
        ows.setLastName(obj.getString("lastName"));
        ows.setProjectType(obj.getString("projectType"));
        ows.setWerks(obj.getString("werks"));
        ows.setWorkshopCode(obj.getString("workshopCode"));
        ows.setProjectStatus(obj.getString("projectStatus"));
        ows.setDateRequired(obj.getString("dateRequired"));
        ows.setProjectCode(obj.getString("projectCode"));
        ows.setJustification(obj.getString("justification"));
        ows.setApplicationDate(obj.getString("applicationDate"));
        ows.setStatus(obj.getString("status"));
        ows.setCreateDate(obj.getString("createDate"));
        ows.setPurchaseLocation(obj.getString("purchaseLocation"));
        //System.out.println(ows.toString());
        return orderWorkshopMapper.createOrderWs(ows);
    }


    public int createOrderWsDtl(JSONArray array, String uuid){
        DecimalFormat df = new DecimalFormat("0.000");
        int res = 0;
        if (array.size() > 0){
            for (int i = 0; i < array.size(); i++){
                JSONObject doc = array.getJSONObject(i);
                OrderWorkshopDtl owsd = new OrderWorkshopDtl();
                owsd.setUuid(uuid);
                //owsd.setRowId(Integer.parseInt(doc.getString("rowId")));
                owsd.setRowId((i + 1) * 10);
                owsd.setMaterialNo(doc.getString("materialNo"));
                owsd.setMaterialZhDesc(doc.getString("materialZhDesc"));
                owsd.setMaterialEnDesc(doc.getString("materialEnDesc"));
                owsd.setRequestQty(Double.parseDouble(doc.getString("requestQty")));
                owsd.setApprovalQty(Double.parseDouble(doc.getString("approvalQty")));
                owsd.setBasicUnit(doc.getString("basicUnit"));
                owsd.setBrand(doc.getString("brand"));
                owsd.setRowStatus(doc.getString("rowStatus"));
                owsd.setRowComment(doc.getString("rowComment"));
                owsd.setDeviceId(doc.getString("deviceId"));
                owsd.setDeviceCategory(doc.getString("deviceCategory"));
                owsd.setDeviceType(doc.getString("deviceType"));
                owsd.setMaterialCategory(doc.getString("materialCategory"));
                owsd.setLongContractCode(doc.getString("longContractCode"));

                res = res + orderWorkshopDtlMapper.insert(owsd);
            }
        }
        return res;
    }

    public void addOrderLog(String userId, String comments, String uuid){
        //OrderLog orderLog = new OrderLog();
        orderLogMapper.insertOrderLog(userId, comments, uuid);
    }

    /** 根据用户传入信息，更新车间请购单表头信息 */
    /**
     * {
     * 	"orderWorkshop": {
     * 	    "uuid":"6013cbd70b6d47debeaa83a77f23657a",
     * 		"spmsWsId": "GH011002-20210203-0005",
     * 		"subject": "GF011002-20210201-车间请购单",
     * 	    "userId": "20001"
     * 		"projectType": "1",
     * 		"projectStatus": "1",
     * 		"dateRequired": "2021-05-01",
     * 		"urgency": "2",
     * 		"projectCode": null,
     * 		"workshopCode": "1002",
     * 		"justification": "申请原因",
     * 		"status": "1",
     *        }
     * }
     * @param doc
     * @return
     */
    @Override
    public ResponseResult updateOrderWorkshop(JSONObject doc) {
        JSONObject json = doc.getJSONObject("orderWorkshop");
        if (null == json){
            return ResponseResult.error("请求参数错误");
        }
        String uuid = json.getString("uuid");
        if (null == uuid){
            return ResponseResult.error("请求参数错误");
        }
        OrderWorkshop ows = new OrderWorkshop();
        ows.setUrgency(json.getString("urgency"));
        ows.setDateRequired(json.getString("dateRequired"));
        ows.setSubject(json.getString("subject"));
        ows.setProjectType(json.getString("projectType"));
        ows.setProjectStatus(json.getString("projectStatus"));
        ows.setProjectCode(json.getString("projectCode"));
        ows.setWorkshopCode(json.getString("workshopCode"));
        ows.setJustification(json.getString("justification"));
        ows.setStatus(json.getString("status"));
        ows.setPurchaseLocation(json.getString("purchaseLocation"));
        int resp = orderWorkshopMapper.update(ows, new QueryWrapper<OrderWorkshop>().eq("UUID", uuid));
        if (resp > 0){
            if (json.getString("status").equals("3")){
                addOrderLog(json.getString("userId"), REJECT_ORDER_WORKSHOP, uuid);
                return ResponseResult.success();
            }
            addOrderLog(json.getString("userId"), UPDATE_ORDER_WORKSHOP_HEAD, uuid);
            return ResponseResult.success();
        }
        return ResponseResult.error();
    }

    @Override
    public void updateOrderWorkshopStatus(String spmsWsId, String status) {
        OrderWorkshop orderWorkshop = new OrderWorkshop();
        orderWorkshop.setStatus(status);
        orderWorkshopMapper.update(orderWorkshop, new QueryWrapper<OrderWorkshop>().eq("SPMS_WS_ID", spmsWsId));
    }

    /**
     * userId 必输；status 必输；
     * @param userId
     * @param status
     * @param pageNo
     * @param pageSize
     * @return
     */
    @Override
    public Map<String, Object> getOrderWSList(String userId, String status, int pageNo, int pageSize) {
        PageHelper.startPage(pageNo, pageSize);
        /** 获取车间请购单表头信息 */
        List<Map<String, Object>> mapList = orderWorkshopMapper.getOrderWSList(userId, status);
        /** 获取车间请购单行项目信息 */
        for (Map<String, Object> map : mapList){
            String uuid = map.get("uuid").toString();
            map.put("orderWorkshopDtl", orderWorkshopDtlMapper.selectList(new QueryWrapper<OrderWorkshopDtl>().eq("UUID", uuid)));
        }
        PageInfo<Map<String, Object>> pageData = new PageInfo<>(mapList);
        Map<String,Object> pageInfo = new HashMap<>();
        pageInfo.put("records", pageData.getList());
        pageInfo.put("total", pageData.getTotal());
        pageInfo.put("size", pageData.getSize());
        pageInfo.put("current", pageData.getPageNum());
        pageInfo.put("pages", pageData.getPages());
        return pageInfo;
    }

    /** 根据车间请购单UUID查询对应工厂请购单SPMS日志信息 示例 ：uuid = 41f9d658ad384b53a2bd9f5daa276405 */
    @Override
    public List<Map<String, Object>> getOrderLogWByUuid(String uuid) {
        return orderWorkshopMapper.getOrderLogWByUuid(uuid);
    }

    /** 根据车间请购单UUID查询对应工厂请购单OA日志信息，示例 ：uuid = fa128e0b2190451483764f715e28cba3 */
    @Override
    public String getOrderLogOaByUuid(String uuid) {
        return orderWorkshopMapper.getOrderLogOaByUuid(uuid);
    }
}
